import React, {Component} from 'react'
import './index.scss'
import MUtil from 'util/mm.jsx'
const _mm = new MUtil()
import User from 'service/user-service.jsx'
const _user = new User();
class Login extends Component {
  constructor(props) {
    super(props)
    this.state = {
      username:'',
      password:'',
      redirect: _mm.getUrlParam('redirect') || '/'
    }
  }

  componentWillMount(){
    document.title = '登录 - happy'
  }
  onInputChange(e){
    let inputValue = e.target.value;
    let inputName = e.target.name;
    this.setState({
      [inputName]:inputValue
    })
  }
  onInputKeyup(e){
    if(e.keyCode ===13 ){
      this.onSubmit()
    }
  }
  onSubmit(){
    let loginInfo = {
      username:this.state.username,
      password: this.state.password
    };
    let checkResult = _user.checkLoginInfo(loginInfo);
    if(checkResult.status){
      _user.login(loginInfo).then((res)=>{
        //登录成功，跳转到原来的页面或进入首页
        console.log(this.state.redirect)
        _mm.setStorage('userInfo', res)
        this.props.history.push(this.state.redirect)
      },(errMsg)=>{
        _mm.errorTips(errMsg)
      })
    }else{
      _mm.errorTips(checkResult.msg)
    }

  }
  render() {
    return (
      <div className='col-md-4 col-md-offset-4'>
        <div className='panel panel-default login-panel'>
          <div className='panel-heading'>欢迎登录</div>
          <div className='panel-body'>
            <div>
              <div className="form-group">
                <input type="text"
                       className="form-control"
                       name='username'
                       placeholder="用户名"
                       onKeyUp ={ e => this.onInputKeyup(e)}
                       onChange={ e => this.onInputChange(e) }
                />
              </div>
              <div className="form-group">
                <input type="password"
                       className="form-control"
                       name='password'
                       placeholder="密码"
                       onKeyUp={ e => this.onInputKeyup(e)}
                       onChange={ e => this.onInputChange(e) }
                />
              </div>
              <button className="btn btn-lg btn-block btn-primary"
                      onClick={ e => this.onSubmit(e)}
              >登录</button>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

export default Login